package _interview150;

import java.util.ArrayList;
import java.util.List;

/**
 * 77. 组合
 */
public class No77 {
    private List<List<Integer>> ans;
    private List<Integer> path;
    private int k;

    /**
     * 1. 枚举选哪个
     */
    public List<List<Integer>> combine1(int n, int k) {
        ans = new ArrayList<>();
        path = new ArrayList<>();
        this.k = k;
        dfs(n);
        return ans;
    }

    private void dfs(int i) {
        if (path.size() == k) {
            ans.add(new ArrayList<>(path));
            return;
        }
        if (i == 0 || path.size() + i < k) return;
        for (int j = i; j > 0; j--) {
            path.add(j);
            dfs(j - 1);
            path.remove(path.size() - 1);
        }
    }

    /**
     * 2. 选或不选
     */
    public List<List<Integer>> combine2(int n, int k) {
        ans = new ArrayList<>();
        path = new ArrayList<>();
        this.k = k;
        dfs2(k);
        return ans;
    }

    private void dfs2(int i) {
        if (path.size() == k) {
            ans.add(new ArrayList<>(path));
            return;
        }
        if (i == 0 || path.size() + i < k) return;
        // 选
        path.add(i);
        dfs2(i - 1);
        path.remove(path.size() - 1);
        // 不选
        dfs2(i - 1);
    }
}
